package top.dreamix.njitkit.ui.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import top.dreamix.njitkit.data.network.Account
import top.dreamix.njitkit.data.network.AccountRepository
import top.dreamix.njitkit.data.network.NetworkSetting
import java.util.UUID

const val NEW_ACCOUNT_ID = "new_account_sentinel" // A unique sentinel value

data class NetworkConfigUiState(
    val allAccounts: List<Account> = emptyList(),
    val selectedAccountId: String = NEW_ACCOUNT_ID,
    val isLoading: Boolean = true,
    val networkSetting: NetworkSetting = NetworkSetting(
        defaultAccountId = null,
        autoLogin = false
    ),
) {
    val isCreateNewMode: Boolean get() = selectedAccountId == NEW_ACCOUNT_ID

    val selectedAccount: Account? get() = allAccounts.find { it.id == selectedAccountId }
}

class NetworkConfigViewModel(application: Application) : AndroidViewModel(application) {

    private val repository = AccountRepository(application)

    private val _selectedAccountId = MutableStateFlow(NEW_ACCOUNT_ID)
    private val _isLoading = MutableStateFlow(true)

    val uiState: StateFlow<NetworkConfigUiState> = combine(
        repository.accountsFlow,
        repository.networkSettingFlow,
        _selectedAccountId,
        _isLoading,
    ) { accounts, networkSetting, selectedId, isLoading ->
        NetworkConfigUiState(
            allAccounts = accounts,
            selectedAccountId = selectedId,
            isLoading = isLoading,
            networkSetting = networkSetting
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = NetworkConfigUiState()
    )

    init {
        viewModelScope.launch {
            val initialAccounts = repository.accountsFlow.first()
            val initialNetworkSetting = repository.networkSettingFlow.first()


            initialNetworkSetting.defaultAccountId?.let {
                _selectedAccountId.value = it
            }
            _isLoading.value = false
        }
    }

    fun selectAccount(accountId: String) {
        _selectedAccountId.value = accountId
    }

    fun saveAccount(account: Account) {
        viewModelScope.launch {
            val currentList = repository.accountsFlow.first().toMutableList()
            val index = currentList.indexOfFirst { it.id == account.id }
            val isNew = index == -1

            if (isNew) {
                currentList.add(account)
            } else {
                currentList[index] = account
            }
            repository.saveAccounts(currentList)
            if (isNew) {
                selectAccount(account.id)
            }
        }
    }

    fun deleteSelectedAccount() {
        viewModelScope.launch {
            val idToDelete = uiState.value.selectedAccountId
            if (idToDelete == NEW_ACCOUNT_ID) return@launch

            val currentList = repository.accountsFlow.first()
            val newList = currentList.filterNot { it.id == idToDelete }
            repository.saveAccounts(newList)
            // Select the first account, or go to create mode if the list is now empty
            _selectedAccountId.value = newList.firstOrNull()?.id ?: NEW_ACCOUNT_ID
        }
    }

    // Methods for global settings
    fun saveNetworkSetting(networkSetting: NetworkSetting) {
        viewModelScope.launch {
            repository.saveNetworkSetting(networkSetting)
        }
    }
}